<template>
  <div class="dynamic-component-container">
    <a-button type="primary" status="success" size="mini" @click="showRemoteComponent = !showRemoteComponent">
      {{ showRemoteComponent?'隐藏': '显示' + '远程组件' }}
    </a-button>
    <RemoteComponent v-if="showRemoteComponent" />
  </div>
</template>

<script setup lang="ts">
import * as Vue from 'vue';
import { defineAsyncComponent } from 'vue';
import { get } from '@/api/http';
import { loadModule } from "vue3-sfc-loader"

const showRemoteComponent = ref(false);

const options = {
  moduleCache: {
    vue: Vue,
  },
  async getFile(url: string) {
    const res = await get({ url })
    // 获取数据
    const componentStr = res.data[0];
    // 创建一个 TextEncoder 实例
    const encoder = new TextEncoder();
    // 将字符串编码为 Uint8Array
    const uint8Array = encoder.encode();
    console.log('Fetched file content:', componentStr); // 确认获取的内容
    return {
      getContentData: (asBinary: any) => asBinary ? uint8Array.buffer : componentStr,
    };
  },
  addStyle(textContent: any) {
    const style = Object.assign(document.createElement("style"), { textContent })
    const ref = document.head.getElementsByTagName("style")[0] || null;
    document.head.insertBefore(style, ref);
  },
  log(type: any, ...args: any) {
        console.log(type, ...args);
      }
}
// 获取动态组件字符串
const RemoteComponent = defineAsyncComponent({
  loader: async () => {
    try {
      // 这里loadModule中url必须是.vue，不知道部署之后是否有一样的问题
      const module = await loadModule("./getDynamicComponentList.vue", options);
      console.log('Loaded module:', module);
      return module;
    } catch (error) {
      console.error('Failed to load module:', error);
      return { template: '<div>Error loading component</div>' }; // Fallback 组件
    }
  },
  loadingComponent: {
    template: '<div>Loading...</div>',
  },
  errorComponent: {
    template: '<div>Error loading component</div>',
  },
})

console.log(RemoteComponent)

</script>

<style lang="less" scoped>

</style>